package app.dws;


import Bean.TrafficHomeDetailPageViewBean;
import app.dwd.BaseAppV1;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import common.Constant;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;

import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

import org.apache.flink.util.Collector;
import util.AtguiguUtil;
import util.FlinkSinkUtil;

import java.time.Duration;

public class Dws_DwsTrafficPageViewWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_DwsTrafficPageViewWindow().init(
                4003,
                2,
                "Dws_03_DwsTrafficPageViewWindow",
                Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 过滤首页和详情页记录
        SingleOutputStreamOperator<JSONObject> homeAndDetailStream=filterHomeAndDetail(stream);
        // 2. 转成一个 pojo
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> beanStream=parseToPojo(homeAndDetailStream);
        // 3. 开窗聚和
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> resultStream=windowAndAgg(beanStream);
        // 4. 写出到 clickhouse 中
        writeToClikehouse(resultStream);
    }
    // 4. 写出到 clickhouse 中
    private void writeToClikehouse(SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> resultStream) {
        resultStream
                .addSink(FlinkSinkUtil.getClickHouseSink("dws_traffic_page_view_window",
                        TrafficHomeDetailPageViewBean.class));
    }

    // 3. 开窗聚和
    private SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> windowAndAgg(SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> beanStream) {
        return beanStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<TrafficHomeDetailPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner((bean,ts)->bean.getTs())
                )
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<TrafficHomeDetailPageViewBean>() {
                            @Override
                            public TrafficHomeDetailPageViewBean reduce(TrafficHomeDetailPageViewBean value1, TrafficHomeDetailPageViewBean value2) throws Exception {
                                value1.setHomeUvCt(value1.getHomeUvCt() + value2.getHomeUvCt());
                                value1.setGoodDetailUvCt(value1.getGoodDetailUvCt() + value2.getGoodDetailUvCt());
                                return value1;
                            }
                        },
                        new ProcessAllWindowFunction<TrafficHomeDetailPageViewBean, TrafficHomeDetailPageViewBean, TimeWindow>() {
                            @Override
                            public void process(Context ctx, Iterable<TrafficHomeDetailPageViewBean> elements, Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                                TrafficHomeDetailPageViewBean bean = elements.iterator().next();
                                bean.setStt(AtguiguUtil.toDatTime(ctx.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDatTime(ctx.window().getEnd()));
                                bean.setTs(System.currentTimeMillis());
                                out.collect(bean);
                            }
                        });
    }

    // 2. 转成一个 pojo
    private SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> parseToPojo(SingleOutputStreamOperator<JSONObject> steam) {
        return steam
                .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
                .process(new KeyedProcessFunction<String, JSONObject, TrafficHomeDetailPageViewBean>() {
                    private ValueState<String> homeState;
                    private ValueState<String> goodDetailState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        homeState = getRuntimeContext().getState(new ValueStateDescriptor<String>("homeState", String.class));
                        goodDetailState = getRuntimeContext().getState(new ValueStateDescriptor<String>("goodDetailState", String.class));
                    }

                    @Override
                    public void processElement(JSONObject value, Context ctx, Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                        Long ts = value.getLong("ts");
                        String pageId = value.getJSONObject("page").getString("page_id");
                        String today = AtguiguUtil.toDate(ts);

                        Long homeUvCt = 0L;
                        String homeDate = homeState.value();
                        if ("home".equals(pageId) && !today.equals(homeDate)) {
                            homeUvCt = 1L;
                            homeState.update(today);
                        }

                        Long goodDetailUvCt = 0L;
                        String goodDetailDate = goodDetailState.value();
                        if ("course_detail".equals(pageId) && !today.equals(goodDetailDate)) {
                            goodDetailUvCt = 1L;
                            goodDetailState.update(today);
                        }
                        TrafficHomeDetailPageViewBean bean = new TrafficHomeDetailPageViewBean("", "", homeUvCt, goodDetailUvCt, ts);
                        if (homeUvCt + goodDetailUvCt == 1) {
                            out.collect(bean);
                        }
                    }
                });
    }

    // 1. 过滤首页和详情页记录
    private SingleOutputStreamOperator<JSONObject> filterHomeAndDetail(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .filter(new FilterFunction<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject value) throws Exception {
                        String pageId=value.getJSONObject("page").getString("page_id");
                        return "home".equals(pageId) || "course_detail".equals(pageId);
                    }
                });
    }
}
